# -*- coding: utf-8 -*-
from flask_whooshalchemyplus import index_all
import multiprocessing
from flask import current_app
import os

from . import celery

INDEX_LOCK_FILE = '/tmp/generate_index.lock'


@celery.task(bind=True)
def generate_index(self):
    lock = multiprocessing.Lock()
    try:
        with lock:
            app = current_app._get_current_object()

            f = open(INDEX_LOCK_FILE, 'w')
            f.write('正在更新索引...')
            f.flush()
            print "正在更新索引..."
            index_all(app)
            if os.path.exists(INDEX_LOCK_FILE):
                os.remove(INDEX_LOCK_FILE)
            f.close()
            print "更新结束"
    except KeyboardInterrupt,e:
        if os.path.exists(INDEX_LOCK_FILE):
            os.remove(INDEX_LOCK_FILE)
    except:
        print '正在运行...'
